﻿using LettuceEncrypt.Accounts;
using Mapster;
using Microsoft.EntityFrameworkCore;
using Quickly.Certs.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Quickly.Certs.EntityFrameworkCore.Data
{
    public class DatabaseAccountRepository : IDatabaseAccountRepository
    {
        public virtual CertsContext Context { get; set; }

        public DatabaseAccountRepository(CertsContext context)
        {
            Context = context;
        }

        public async Task<AccountModel?> GetAccountModelAsync(CancellationToken cancellationToken)
        {
            var account = await Context.Accounts.AsNoTracking()
                .ProjectToType<AccountModel>()
                .FirstOrDefaultAsync(cancellationToken);

            return account;
        }

        public async Task SaveAccountModelAsync(AccountModel account, CancellationToken cancellationToken)
        {
            var current = await Context.Accounts.Where(x => x.Id == account.Id).FirstOrDefaultAsync();
        
            if(current == null)
            {
                current = new AccountEntity()
                {
                    Id = account.Id,
                    PrivateKey = account.PrivateKey,
                    EmailAddresses = account.EmailAddresses,
                };

                Context.Add(current);
            }
            else
            {
                current.PrivateKey = account.PrivateKey;
                current.EmailAddresses = account.EmailAddresses;
                current.LastModified = DateTimeOffset.UtcNow;
            }

            await Context.SaveChangesAsync(cancellationToken);
        }
    }
}
